#include "sessiontable.h"
#include "sqlitemanager.h"
#include <QDebug>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlRecord>

 namespace Sqlite{

SessionTable::SessionTable(QObject *parent) :
    QObject(parent)
{
    qDebug() << "SessionTable" ;
}


void SessionTable::createTable()
{

    QSqlQuery qry;
    qry.prepare( "CREATE TABLE IF NOT EXISTS session (id INTEGER PRIMARY KEY, svalue NVARCHAR(100))" );
    SqliteManager::instance()->doProcessSQLQuery(qry);


}

SessionInfo SessionTable::getSessionInfo()
{
    QSqlQuery qry;
    qry.prepare( "SELECT * FROM session" );
    SqliteManager::instance()->doProcessSQLQuery(qry);

    qDebug() << qry.lastError();


    QSqlRecord rec = qry.record();

    int cols = rec.count();

   // for( int c=0; c<cols; c++ )
   //    qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );
    SessionInfo sInfo;
    for( int r=0; qry.next(); r++ )
    {
        sInfo.sessionKey = qry.value(1).toString();
        sInfo.useId = qry.value(0).toInt();
        return sInfo;
    }

    return sInfo;

}

void SessionTable::updateSession(const int userId, const QString& sessionValue){


    QSqlQuery qry;
    QString strdeleteAll("delete from session");
    qry.prepare(strdeleteAll);
    SqliteManager::instance()->doProcessSQLQuery(qry);

    QString str = QString("INSERT OR REPLACE INTO session (id, svalue) VALUES (%1, '%2')").arg(userId).arg(sessionValue);
    qry.prepare(str);
    SqliteManager::instance()->doProcessSQLQuery(qry);

}

void SessionTable::clearTable()
{
    QSqlQuery qry;
    QString strdeleteAll("delete from session");
    qry.prepare(strdeleteAll);
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

}
